import axiosObj from "axios";

const defaultConfig = {
  timeout: 60*1000,
  headers: {
    get: {
      // 设置默认请求头，当需要特殊请求头时，将其作为参数传入，即可覆盖此处的默认参数
      "Content-Type": "application/json;charset=utf-8"
    },
    post:{
      // 设置默认请求头，当需要特殊请求头时，将其作为参数传入，即可覆盖此处的默认参数(第三个参数即config)
      "Content-Type": "application/json;charset=utf-8"
    }
  }
};

const _axios = axiosObj.create(defaultConfig);
// request拦截器
_axios.interceptors.request.use(
  function(config){
    const controller = new AbortController();
    config.signal = controller.signal;
    let token = sessionStorage.getItem('token');
    token && (config.headers.Authorization = token);

    return config;
  },
  function (error){
    error.data = {};
    error.data.msg = "服务器异常";
    return Promise.reject(error);
  }
);

// response拦截器
_axios.interceptors.response.use(
  function (response){
    if(response.status === 200){
      return response.data;
    }
    return response;
  },
  function (error){
    if (error) {
      return Promise.reject(error);
    } else {
      // 断网
      return Promise.reject(error);
    }
  }
);
export default _axios;
